

#include <objectmanager.h>
#include <session.h>

#include <QDomDocument>
#include <QDomElement>
#include <QFile>

void ObjectManager::Save()
{
  QDomDocument doc ("objects");

  QDomElement objectsElements = doc.createElement("objects");

  foreach (SceneObject *object, _objects)
    {
      QDomElement objectElement = doc.createElement("object");
      objectElement.setAttribute("name", object->GetName());
      objectElement.setAttribute("category", object->GetCategory().GetFullName());

      QDomElement objectFilenameElement = doc.createElement("filename");
      objectFilenameElement.appendChild(doc.createTextNode(object->GetFilename()));
      objectElement.appendChild(objectFilenameElement);

      objectsElements.appendChild(objectElement);
    }
  doc.appendChild(objectsElements);

  QFile file (Session::Get()->GetProjectFolder() + "/objects.xobjs");
  if (!file.open(QIODevice::WriteOnly))
    {
      return;
    }

  file.write(doc.toByteArray(4));
  file.close();
}

bool ObjectManager::Load()
{
  QFile file (Session::Get()->GetProjectFolder() + "/objects.xobjs");
  if (!file.open(QIODevice::ReadOnly))
    {
      return false;
    }

  QDomDocument doc;
  if (!doc.setContent(&file))
    {
      file.close();
      return false;
    }
  file.close();

  QDomElement objectsElement = doc.documentElement();
  if (objectsElement.tagName() != "objects")
    {
      return false;
    }

  for (QDomElement objectElement = objectsElement.firstChildElement("object");
       !objectElement.isNull();
       objectElement = objectElement.nextSiblingElement("object"))
    {
      if (    !objectElement.hasAttribute("name")
              ||  !objectElement.hasAttribute("category"))
        {
          continue;
        }

      QDomElement objectFilenameElement = objectElement.firstChildElement("filename");
      if (objectFilenameElement.isNull())
        {
          continue;
        }
      QString name = objectElement.attribute("name");
      QString category = objectElement.attribute("category");
      QString filename = objectFilenameElement.text();

      SceneObject *sceneObject = new SceneObject();
      sceneObject->SetCategory(Category (category));
      sceneObject->SetName(name);
      sceneObject->SetFilename(filename);

      AddObject(sceneObject);

    }

  return true;
}
